<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="企业名称" prop="companyName">
        <el-input
          v-model="queryParams.companyName"
          placeholder="请输入企业名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="企业类型" prop="companyType">
        <el-select v-model="queryParams.companyTypeId" placeholder="请选择企业类型" clearable>
          <el-option
            v-for="dict in dict.type.company_type"
            :key="dict.companyTypeId"
            :label="dict.companyType"
            :value="dict.companyTypeId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="企业标签" prop="companyTag">
        <el-input
          v-model="queryParams.companyTagDisplayText"
          placeholder="请选择企业标签"
          readonly
          @click="handleTagSelect"
          style="cursor: pointer;"
        >
          <el-button slot="append" icon="el-icon-search" @click="handleTagSelect"></el-button>
        </el-input>
      </el-form-item>
      <!-- <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.company_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-message" size="mini" @click="handleBatchMessage">群发消息</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-document" size="mini" @click="handleViewMessageLogs">查看消息记录</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="companyList" @selection-change="handleSelectionChange" style="width: 100%">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="企业ID" width="80" align="center" prop="id" />
      <el-table-column label="企业名称" min-width="200" align="center" prop="companyName" show-overflow-tooltip>
        <template slot-scope="scope">
          <span class="company-name-cell" :title="scope.row.companyName">{{ scope.row.companyName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="企业类型" width="150" align="center" prop="companyType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.company_type" :value="scope.row.companyType"/>
        </template>
      </el-table-column>
      <el-table-column label="统一社会信用代码" min-width="180" align="center" prop="uniscid" show-overflow-tooltip>
        <template slot-scope="scope">
          <span class="credit-code-cell" :title="scope.row.uniscid">{{ scope.row.uniscid }}</span>
        </template>
      </el-table-column>
      <el-table-column label="联系人" width="100" align="center" prop="contact" show-overflow-tooltip>
        <template slot-scope="scope">
          <span :title="scope.row.contact">{{ scope.row.contact }}</span>
        </template>
      </el-table-column>
      <el-table-column label="联系电话" width="130" align="center" prop="contactPhone" show-overflow-tooltip>
        <template slot-scope="scope">
          <span :title="scope.row.contactPhone">{{ scope.row.contactPhone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="地址" min-width="200" align="center" prop="address" show-overflow-tooltip>
        <template slot-scope="scope">
          <span class="address-cell" :title="scope.row.address">{{ scope.row.address }}</span>
        </template>
      </el-table-column>
      <el-table-column label="联企人员" width="100" align="center" prop="memberName" show-overflow-tooltip>
        <template slot-scope="scope">
          <span :title="scope.row.memberName">{{ scope.row.memberName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160" fixed="right">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" style="width: 3rem;" @click="handleDetail(scope.row)">详情</el-button>
          <el-dropdown trigger="click" @command="(cmd) => handleMore(cmd, scope.row)">
            <el-button size="mini" style="width: 4rem;">
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="edit"><i class="el-icon-edit"></i> 编辑</el-dropdown-item>
              <el-dropdown-item command="tag"><i class="el-icon-collection-tag"></i> 企业标签</el-dropdown-item>
              <el-dropdown-item command="delete"><i class="el-icon-delete"></i> 删除企业</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />

    <!-- 企业标签选择组件 -->
    <tag-select
      :visible.sync="tagDialogVisible"
      :value="queryParams.companyTag"
      @confirm="handleTagConfirm"
      @cancel="handleTagCancel"
      @close="handleTagClose"
    />

    <!-- 编辑企业信息对话框 -->
    <el-dialog 
      title="编辑信息" 
      :visible.sync="editDialogVisible" 
      width="650px" 
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form ref="editForm" :model="editForm" :rules="editRules" label-width="140px">
        <!-- Logo上传 -->
        <el-form-item label="Logo">
          <div class="logo-upload-container">
            <div class="logo-preview" v-if="editForm.logo">
              <img :src="editForm.logo" alt="企业Logo" style="width: 64px; height: 64px; border-radius: 4px;" />
            </div>
            <div>
              <el-upload
                class="logo-uploader"
                action="#"
                :show-file-list="false"
                :before-upload="beforeLogoUpload"
                :http-request="handleLogoUpload"
                accept=".jpg,.jpeg,.png"
              >
                <el-button size="small" type="primary" plain>上传Logo</el-button>
              </el-upload>
              <div class="upload-tip">建议尺寸: 64*64像素,只能上传jpg/png文件,且不超过500kb</div>
            </div>
          </div>
        </el-form-item>

        <!-- 企业名称 -->
        <el-form-item label="企业名" prop="companyName">
          <el-input v-model="editForm.companyName" placeholder="请输入企业名称" />
        </el-form-item>

        <!-- 统一社会信用代码 -->
        <el-form-item label="统一社会信用代码" prop="uniscid">
          <el-input v-model="editForm.uniscid" placeholder="请输入统一社会信用代码" />
        </el-form-item>

        <!-- 地址 -->
        <el-form-item label="地址" prop="address">
          <el-input v-model="editForm.address" placeholder="请输入地址" />
        </el-form-item>

        <!-- 企业类型 -->
        <el-form-item label="企业类型" prop="companyTypeId">
          <el-select v-model="editForm.companyTypeId" placeholder="请选择企业类型" style="width: 100%">
            <el-option
              v-for="dict in dict.type.company_type"
              :key="dict.companyTypeId"
              :label="dict.companyType"
              :value="dict.companyTypeId"
            />
          </el-select>
        </el-form-item>

        <!-- 联系人 -->
        <el-form-item label="联系人" prop="contact">
          <el-input v-model="editForm.contact" placeholder="请输入联系人" />
        </el-form-item>

        <!-- 联系电话 -->
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="editForm.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>

        <!-- 企业网址 -->
        <el-form-item label="企业网址" prop="website">
          <el-input v-model="editForm.website" placeholder="请输入企业网址" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleEditCancel">取消</el-button>
        <el-button type="primary" @click="handleEditSubmit" :loading="editSubmitting">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { companyList, auditCompany, getCompanyDetail, addCompany, updateCompany, delCompany, companyTypeList } from "@/api/biz/api";
import TagSelect from "@/components/TagSelect";

export default {
  name: "CompanyList",
  components: {
    TagSelect
  },
  dicts: ['company_type', 'company_status'],
  data() { 
     return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 企业表格数据
      companyList: [],
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        companyName: null,
        companyTypeId: null,
        companyTag: null,
        companyTagText: [], // 存储conditions数组用于查询
        companyTagDisplayText: '', // 存储显示文本用于输入框显示
        tagValCond: null,
        status: 1,
        showFlag: 1

      },
      // 标签选择弹框相关
      tagDialogVisible: false,
      // 编辑对话框相关
      editDialogVisible: false,
      editSubmitting: false,
      editForm: {
        id: null,
        companyName: '',
        uniscid: '',
        address: '',
        companyTypeId: null,
        contact: '',
        contactPhone: '',
        website: '',
        logo: ''
      },
      editRules: {
        companyName: [
          { required: true, message: '企业名称不能为空', trigger: 'blur' }
        ],
        uniscid: [
          { required: true, message: '统一社会信用代码不能为空', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '地址不能为空', trigger: 'blur' }
        ],
        companyTypeId: [
          { required: true, message: '企业类型不能为空', trigger: 'change' }
        ],
        contact: [
          { required: true, message: '联系人不能为空', trigger: 'blur' }
        ],
        contactPhone: [
          { required: true, message: '联系电话不能为空', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    // 加载基础数据，然后加载企业列表
    this.getCompanyTypeList().then(() => {
      this.getList();
    }).catch(error => {
      console.error('加载基础数据失败:', error);
      // 即使基础数据加载失败，也要尝试加载企业列表
      this.getList();
    });
  },
  methods: {
    /** 查询企业类型列表 */
    getCompanyTypeList() {
      return companyTypeList().then(response => {
        if (response.code === 200) {
          // 将企业类型数据转换为字典格式
          const typeData = response.data || [];
          this.dict.type.company_type = typeData.map(item => ({
            companyTypeId: item.id,
            companyType: item.typeName,
            label: item.typeName,
            value: item.id
          }));
        }
        return response;
      }).catch(error => {
        console.error('获取企业类型列表失败:', error);
        this.dict.type.company_type = [];
        return Promise.reject(error);
      });
    },
    /** 查询企业列表 */
    getList() {
      this.loading = true;
      // 构建查询参数，确保与后端接口匹配
      const params = {
        current: this.queryParams.current,
        size: this.queryParams.size,
        companyName: this.queryParams.companyName,
        companyTypeId: this.queryParams.companyTypeId,
        tagValCond: this.queryParams.companyTagText, // companyTagText现在存储的是conditions数组
        status: this.queryParams.status,
        showFlag: this.queryParams.showFlag,
      };
      
      companyList(params).then(response => {
        console.log('企业列表 ：',response);
        
        this.companyList = response.data?.records || [];
        this.total = response.data?.total || 0;
        this.loading = false;
      }).catch(error => {
        console.error('获取企业列表失败:', error);
        this.companyList = [];
        this.total = 0;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        companyName: null,
        companyType: null,
        contactPerson: null,
        contactPhone: null,
        status: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        current: 1,
        size: 10,
        companyName: null,
        companyTypeId: null,
        companyTag: null,
        companyTagText: [],
        companyTagDisplayText: '',
        tagValCond: null,
        status: 1,
        showFlag: 1
      };
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加企业";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCompanyDetail(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改企业";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCompany(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCompany(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除企业编号为"' + ids + '"的数据项？').then(function() {
        return delCompany(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 详情
    handleDetail(row) {
      this.$router.push({
        path: `/mp/companyuser/detail/${row.id}`
      });
      // this.$router.push({ 
      //   path: '/mp/companyuser/detail',
      //   query: {
      //     companyId: row.id,
      //     companyData: encodeURIComponent(JSON.stringify({
      //       id: row.id,
      //       companyName: row.companyName,
      //       uniscid: row.uniscid,
      //       address: row.address,
      //       contact: row.contact,
      //       contactPhone: row.contactPhone,
      //       website: row.website,
      //       companyType: row.companyType,
      //       introduction: row.introduction || '',
      //       updateTime: row.updateTime || ''
      //     }))
      //   }
      // })
    },
    // 顶部按钮
    handleBatchMessage() {
      this.$modal.msg('TODO: 群发消息');
    },
    handleExport() {
      this.$modal.msg('TODO: 导出');
    },
    handleViewMessageLogs() {
      this.$modal.msg('TODO: 查看消息记录');
    },
    // 更多下拉
    handleMore(command, row) {
      if (command === 'edit') {
        this.handleEdit(row)
      } else if (command === 'tag') {
        this.$modal.msg('TODO: 企业标签设置');
      } else if (command === 'delete') {
        this.handleDelete(row)
      }
    },
    // 打开标签选择弹框
    handleTagSelect() {
      this.tagDialogVisible = true;
    },
    // 标签选择确认
    handleTagConfirm(result) {
      console.log('标签选择确认，返回数据:', result);
      // 将conditions数组传入companyTagText用于查询
      this.queryParams.companyTagText = result.conditions || [];
      // 保存显示文本用于输入框显示
      this.queryParams.companyTagDisplayText = result.displayText || '';
      // 保存原始数据用于编辑回显
      this.queryParams.companyTag = result.conditions;
      
      // 执行查询
      this.handleQuery();
    },
    // 标签选择取消
    handleTagCancel() {
      // 可以在这里处理取消逻辑
    },
    // 标签选择关闭
    handleTagClose() {
      // 可以在这里处理关闭逻辑
    },
    // 编辑企业信息
    handleEdit(row) {
      // 获取企业详情并回填数据
      getCompanyDetail(row.id).then(response => {
        if (response.code === 200) {
          const companyData = response.data;
          this.editForm = {
            id: companyData.id,
            companyName: companyData.companyName || '',
            uniscid: companyData.uniscid || '',
            address: companyData.address || '',
            companyTypeId: companyData.companyTypeId || null,
            contact: companyData.contact || '',
            contactPhone: companyData.contactPhone || '',
            website: companyData.website || '',
            logo: companyData.companyLogoUrl || ''
          };
          this.editDialogVisible = true;
        } else {
          this.$modal.msgError('获取企业详情失败');
        }
      }).catch(error => {
        console.error('获取企业详情失败:', error);
        this.$modal.msgError('获取企业详情失败');
      });
    },
    // 取消编辑
    handleEditCancel() {
      this.editDialogVisible = false;
      this.resetEditForm();
    },
    // 重置编辑表单
    resetEditForm() {
      this.editForm = {
        id: null,
        companyName: '',
        uniscid: '',
        address: '',
        companyTypeId: null,
        contact: '',
        contactPhone: '',
        website: '',
        logo: ''
      };
      this.$nextTick(() => {
        this.$refs.editForm && this.$refs.editForm.clearValidate();
      });
    },
    // 提交编辑
    handleEditSubmit() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          this.editSubmitting = true;
          updateCompany(this.editForm).then(response => {
            if (response.code === 200) {
              this.$modal.msgSuccess('修改成功');
              this.editDialogVisible = false;
              this.getList(); // 刷新表格
              this.resetEditForm();
            } else {
              this.$modal.msgError(response.msg || '修改失败');
            }
          }).catch(error => {
            console.error('修改企业失败:', error);
            this.$modal.msgError('修改失败');
          }).finally(() => {
            this.editSubmitting = false;
          });
        }
      });
    },
    // Logo上传前验证
    beforeLogoUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt500K = file.size / 1024 < 500;

      if (!isJPG) {
        this.$modal.msgError('Logo只能是 JPG/PNG 格式!');
        return false;
      }
      if (!isLt500K) {
        this.$modal.msgError('Logo大小不能超过 500KB!');
        return false;
      }
      return true;
    },
    // Logo上传处理
    handleLogoUpload(file) {
      // 这里需要根据实际的上传接口来实现
      // 暂时使用本地预览
      const reader = new FileReader();
      reader.onload = (e) => {
        this.editForm.logo = e.target.result;
      };
      reader.readAsDataURL(file.file);
      this.$modal.msgSuccess('Logo上传成功');
    }
  }
};
</script>

<style scoped>
/* 表格样式优化 */
.el-table .cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  padding: 0 8px;
}

/* 确保表格单元格内容不换行 */
.el-table td .cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 企业名称列特殊处理 */
.el-table .company-name-cell {
  max-width: 200px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: inline-block;
}

/* 地址列特殊处理 */
.el-table .address-cell {
  max-width: 250px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: inline-block;
}

/* 统一社会信用代码列特殊处理 */
.el-table .credit-code-cell {
  max-width: 180px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: inline-block;
}

/* 编辑对话框样式 */
.logo-upload-container {
  display: flex;
  align-items: center;
  gap: 16px;
}

.logo-preview {
  display: flex;
  align-items: center;
}

.logo-uploader {
  display: flex;
  align-items: center;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.dialog-footer {
  text-align: right;
  padding: 20px 0 0 0;
}

.dialog-footer .el-button {
  margin-left: 10px;
}

/* 表单样式优化 */
.el-form-item__label {
  font-weight: 500;
}

.el-form-item {
  margin-bottom: 20px;
}
</style>
